package com.tz.cartelo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tz.cartelo.BaseApplication;
import com.tz.cartelo.R;
import com.tz.cartelo.constant.Api;
import com.tz.cartelo.constant.Key;
import com.tz.cartelo.model.DataParams;
import com.tz.cartelo.result.ResultGetCode;
import com.tz.cartelo.util.CommonUtils;
import com.tz.common.util.LogUtil;
import com.tz.common.util.PreferencesUtils;
import com.tz.common.util.VolleyDataUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/4/16.
 */

public class ChangePhoneActivity extends DataLoadActivity implements View.OnClickListener {
    private static final String TAG = "ChangePhoneActivity";
    private static final int CHANGE_PASSWORD = 1;
    private static final int HANDLER_TIMER = 1;
    private EditText mChangePhoneCode, mChangePhonePhoneEdit;
    private ImageView mChangePhoneCodeClean;
    private TextView mChangePhoneGetCode;
    private Api mApi;
    private String mCode;
    private Timer mTimer;
    private MyTimerTask myTimerTask;
    private int countdown = 60;
    private boolean mIsGettingCode;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_change_phone;
    }

    @Override
    protected void init() {
        BaseApplication.addActivity(this);
        mChangePhonePhoneEdit = (EditText) findViewById(R.id.change_phone_phone_edit);
        TextView mChangePhonePhone = (TextView) findViewById(R.id.change_phone_phone_text);
        mChangePhonePhone.setText(PreferencesUtils.getString(Key.PER_USER_PHONE, ""));
        if (getIntent().getFlags() == Key.BIND_PHONE_CHANGE_PHONE) {
            mChangePhonePhoneEdit.setVisibility(View.VISIBLE);
            mChangePhonePhone.setVisibility(View.GONE);
        } else {
            mChangePhonePhoneEdit.setVisibility(View.GONE);
            mChangePhonePhone.setVisibility(View.VISIBLE);
        }

        mChangePhoneCode = (EditText) findViewById(R.id.change_phone_code);
        mChangePhoneCodeClean = (ImageView) findViewById(R.id.change_phone_code_clean);
        mChangePhoneGetCode = (TextView) findViewById(R.id.change_phone_get_code);
        mChangePhoneGetCode.setOnClickListener(this);
        mChangePhoneCodeClean.setOnClickListener(this);
        findViewById(R.id.change_phone_send).setOnClickListener(this);
        mChangePhoneCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    mChangePhoneCodeClean.setVisibility(View.VISIBLE);
                else
                    mChangePhoneCodeClean.setVisibility(View.GONE);
            }
        });

        mTimer = new Timer();
    }

    @Override
    protected void initTitle() {
        ImageView titleBack = (ImageView) findViewById(R.id.title_back);
        titleBack.setVisibility(View.VISIBLE);
        titleBack.setOnClickListener(this);

        TextView titleText = (TextView) findViewById(R.id.title_text);
        if (getIntent().getFlags() == Key.BIND_PHONE_CHANGE_PHONE)
            titleText.setText(R.string.change_phone_title);
        else
            titleText.setText("安全校验");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.change_phone_code_clean:
                mChangePhoneCode.setText("");
                break;
            case R.id.change_phone_get_code:
                if (getIntent().getFlags() == Key.BIND_PHONE_CHANGE_PHONE) {
                    if (countdown != 60) {
                        showToast("请在倒计时结束后获取验证码");
                    } else if (mChangePhonePhoneEdit.getText().toString().trim().isEmpty()) {
                        showToast(R.string.change_phone_input_phone);
                    } else if (!CommonUtils.isPhoneNum(mChangePhonePhoneEdit.getText().toString().trim())) {
                        showToast(R.string.login_wrong_phone);
                    } else {
                        mApi = Api.GET_PHONE_CODE;
                        loadData(mApi, true);
                    }
                } else {
                    if (countdown != 60) {
                        showToast("请在倒计时结束后获取验证码");
                    } else {
                        mApi = Api.GET_PHONE_CODE;
                        loadData(mApi, true);
                    }
                }

                break;
            case R.id.change_phone_send:
                if (CommonUtils.isEmpty(mCode)) {
                    showToast(R.string.safe_test_get_code_first);
                } else if (mChangePhoneCode.getText().toString().trim().isEmpty()) {
                    showToast(R.string.safe_test_code);
                } else {
                    mApi = Api.CHANGE_PHONE;
                    loadData(mApi, true);
                }
                break;
            default:
                break;
        }
    }

    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            Message message = new Message();
            message.what = HANDLER_TIMER;
            handler.sendMessage(message);
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_TIMER:
                    countdown--;
                    mChangePhoneGetCode.setText(countdown + "s");
                    if (0 == countdown) {
                        if (myTimerTask != null && mTimer != null) {
                            myTimerTask.cancel(); //退出计时器
                            myTimerTask = null;
                            mChangePhoneGetCode.setText(getString(R.string.safe_test_get_code));
                            countdown = 60;
                        }
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void initParams(DataParams params) {
        switch (mApi) {
            case GET_PHONE_CODE:
                VolleyDataUtils.mHeaders.put("Cookie", "JSESSIONID=" + PreferencesUtils.getString(Key.SESSION_ID, ""));
                if (getIntent().getFlags() == Key.BIND_PHONE_CHANGE_PHONE) {
                    params.addParam("phone", mChangePhonePhoneEdit.getText().toString().trim());
                    params.addParam("userId", PreferencesUtils.getString(Key.PER_USER_ID, ""));
                    params.addParam("type", "2");
                    params.addParam("uniqueIdentifier", getIntent().getStringExtra("uniqueIdentifier"));
                } else {
                    params.addParam("userId", PreferencesUtils.getString(Key.PER_USER_ID, ""));
                    params.addParam("type", "1");
                }
                break;
            case CHANGE_PHONE:
                VolleyDataUtils.mHeaders.put("Cookie", "JSESSIONID=" + PreferencesUtils.getString(Key.SESSION_ID, ""));
                if (getIntent().getFlags() == Key.BIND_PHONE_CHANGE_PHONE) {
                    params.addParam("phone", mChangePhonePhoneEdit.getText().toString().trim());
                    params.addParam("userId", PreferencesUtils.getString(Key.PER_USER_ID, ""));
                    params.addParam("type", "2");
                    params.addParam("code", mChangePhoneCode.getText().toString().trim());
                    params.addParam("uniqueIdentifier", mCode);
                } else {
                    params.addParam("userId", PreferencesUtils.getString(Key.PER_USER_ID, ""));
                    params.addParam("type", "1");
                    params.addParam("code", mChangePhoneCode.getText().toString().trim());
                    params.addParam("uniqueIdentifier", mCode);
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void disposeResult(Api api, String response) {
        LogUtil.d(TAG, response);
        ResultGetCode resultGetCode;
        switch (api) {
            case GET_PHONE_CODE:
                resultGetCode = fromJson(response, ResultGetCode.class);
                if (!resultGetCode.isSuccess()) {
                    showToast(resultGetCode.getMessage());
                    return;
                }
                showToast(R.string.safe_test_get_code_succeed);
                mCode = resultGetCode.getGetCode().getUniqueIdentifier();
                if (myTimerTask == null) {
                    myTimerTask = new MyTimerTask();
                    mTimer.schedule(myTimerTask, 0, 1000); //延时0ms后执行，1000ms执行一次
                }
                mIsGettingCode = true;
                break;
            case CHANGE_PHONE:
                resultGetCode = fromJson(response, ResultGetCode.class);
                if (!resultGetCode.isSuccess()) {
                    showToast(resultGetCode.getMessage());
                    return;
                }
                if (getIntent().getFlags() == Key.BIND_PHONE_CHANGE_PHONE) {
                    showToast("更改手机号成功");
                    PreferencesUtils.clearPre();//清空本地保存数据
                    BaseApplication.clearActivity();
                    switchActivityAndFinish(LoginActivity.class, null);
                } else {
                    showToast("验证手机号成功");
                    Bundle bundle = new Bundle();
//                    bundle.putString("uniqueIdentifier", mCode);
                    bundle.putString("uniqueIdentifier", resultGetCode.getGetCode().getUniqueIdentifier());
                    switchActivityForResult(ChangePasswordActivity.class, CHANGE_PASSWORD, bundle);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHANGE_PASSWORD:
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

}
